﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using fResApp.Helpers;
using Panuon.UI.Silver;
using CommonLibrary.Date;
using fResApp.ModelDot;
using BLL;
using Common;
using ServiceLibrary.Implements;
using ServiceLibrary.DtoModel;
using KBZ.Common;
using ServiceLibrary.DtoModel.DeskApp;
using System.Globalization;

namespace fResApp.PartialViews.Business
{
    /// <summary>
    /// TableRooms.xaml 的交互逻辑
    /// </summary>
    public partial class CanTaiGuanLi : UserControl
    {
        #region property
        private int _roomType = 0;
        public double _CostMoney = 0;
        public static string PaymentParm { get; set; }
        List<sysMenusDto> OrderInfolst = new List<sysMenusDto>();
        List<sysBillConsumeDto> CostOrderList = new List<sysBillConsumeDto>();
        public List<TableModel> TableDataList { get; set; } = new List<TableModel>();
        sysRoomsService roomservice = new sysRoomsService();
        sysRoomTypeService roomTypeService = new sysRoomTypeService();
        sysMenutypeService menutypeService = new sysMenutypeService();
        sysMenuService menuService = new sysMenuService();
        sysOpenBillsService openBillsService = new sysOpenBillsService();
        sysBillConsumeService billConsumeService = new sysBillConsumeService();
        #endregion

        public CanTaiGuanLi()
        {
            InitializeComponent();
            DataContext = this;
            tabInfoHead.Visibility = Visibility.Collapsed;
            tableInfoList.Visibility = Visibility.Collapsed;
            costSumInfo.Visibility = Visibility.Collapsed;
            proTypes.Visibility = Visibility.Collapsed;
            proList.Visibility = Visibility.Collapsed;
            tabInfoHead.Visibility = Visibility.Collapsed;
            OpenTableOrderInfo.Visibility = Visibility.Collapsed;
            getTableData();
        }

        #region Event
        /// <summary>
        /// 餐桌类型点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RoomTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!IsLoaded) return;
            var _curTabItem = (TabItem)RoomTypes.SelectedItem;
            string strRoomType = _curTabItem.Header != null ? _curTabItem.Header.ToString() : "";
            var _queryRes = roomTypeService.GetModelAsync("  rtName='" + strRoomType + "' ").Result;
            if (_queryRes.statusCode == (int)ApiEnum.Status)
            {
                var roomTypeObj = _queryRes.data;
                var _roomTypeId = roomTypeObj != null ? roomTypeObj.rtGuid : string.Empty;
                var _rtstate = roomTypeObj != null && _roomTypeId != null ? 5 : -1;
                getRooms(_roomTypeId, _rtstate);
            }

        }
        /// <summary>
        /// 商品类型点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var _curTabItem = (TabItem)proTypes.SelectedItem;
            string strProType = _curTabItem.Header != null ? _curTabItem.Header.ToString() : "";
            var _mtid = _curTabItem.Uid != null ? _curTabItem.Uid.ToString() : "";
            GetProList(_mtid);
        }
        /// <summary>
        /// 餐桌点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListBoxMouseDouleClick(object sender, EventArgs e)
        {
            if (sender is ListBoxItem)
            {
                ListBoxItem curTableObj = (ListBoxItem)sender;
                var curTableInfo = curTableObj.Content;
                if (curTableInfo is TableModel)
                {
                    var tableObj = (TableModel)curTableInfo;
                    if (tableObj != null)
                    {
                        btnOrderNo.Content = tableObj.tbOrderNo;
                        switch (tableObj.tbStateName)
                        {
                            case "空闲":
                                OpenTableInfo.Visibility = Visibility.Visible;
                                tabInfoHead.Visibility = Visibility.Collapsed;
                                tableInfoList.Visibility = Visibility.Collapsed;
                                costSumInfo.Visibility = Visibility.Collapsed;
                                break;
                            case "用餐中":
                                OpenTableInfo.Visibility = Visibility.Collapsed;
                                OpenTableOrderInfo.Visibility = Visibility.Collapsed;
                                tabInfoHead.Visibility = Visibility.Visible;
                                tableInfoList.Visibility = Visibility.Visible;
                                costSumInfo.Visibility = Visibility.Visible;
                                break;
                            case "预约中":
                                OpenTableInfo.Visibility = Visibility.Visible;
                                tabInfoHead.Visibility = Visibility.Collapsed;
                                tableInfoList.Visibility = Visibility.Collapsed;
                                costSumInfo.Visibility = Visibility.Collapsed;
                                break;
                            case "待清理":
                                OpenTableInfo.Visibility = Visibility.Visible;
                                tabInfoHead.Visibility = Visibility.Collapsed;
                                tableInfoList.Visibility = Visibility.Collapsed;
                                costSumInfo.Visibility = Visibility.Collapsed;
                                break;
                            case "已停用":
                                Notice.Show("当前餐桌已停用，请选择其他可用餐桌！", "提示", 3, MessageBoxIcon.Warning);
                                break;
                        }
                        var _userNum = 0;
                        int.TryParse(tableObj.tbMaxNum.ToString(), out _userNum);
                        btnTableNo.Content = tableObj.tbName;
                        btnTableNo.Uid = tableObj.tbId.ToString();
                        txtAmountUser.Text = _userNum.ToString();
                        txtNumOrder.Text = _userNum.ToString();
                        txtAmountTime.Text = tableObj.userTime.Replace("分钟", "");
                        GetDetail(tableObj.tbOrderNo);
                    }
                }
            }
        }
        /// <summary>
        /// 产品列表中，单个产品的选中和取消选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SignProClick(object sender, EventArgs e)
        {
            if (sender is ListBoxItem)
            {
                ListBoxItem curTableObj = (ListBoxItem)sender;
                var curProInfo = curTableObj.Content;
                sysMenusDto _curProObj = null;
                try
                {
                    _curProObj = (sysMenusDto)curProInfo;
                }
                catch
                {
                    Notice.Show("当前菜品不可用，请选择其他菜品！", "提示", 3, MessageBoxIcon.Error);
                    return;
                }
                if (_curProObj.msScalar == 0)
                {
                    Notice.Show("当前菜品库存不足，请选择其他菜品！", "提示", 3, MessageBoxIcon.Error);
                    return;
                }
                ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(curTableObj);
                DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
                StackPanel _proNumBlock = (StackPanel)myDataTemplate.FindName("ProNumBlock", myContentPresenter);

                orderInfoList.ItemsSource = null;
                if (_proNumBlock.IsVisible)//取消产品
                {
                    _proNumBlock.Visibility = Visibility.Collapsed;
                    var _proselLen = OrderInfolst.Count;
                    for (int i = _proselLen - 1; i >= 0; i--)
                    {
                        var _proItem = (sysMenusDto)OrderInfolst[i];
                        if (_proItem.proGuid == _curProObj.proGuid)
                        {
                            OrderInfolst.Remove(OrderInfolst[i]);
                        }
                    }
                }
                else//选中产品
                {
                    _proNumBlock.Visibility = Visibility.Visible;
                    sysMenusDto buyProObj = new sysMenusDto
                    {
                        proGuid = _curProObj.proGuid,
                        msName = _curProObj.msName,
                        msPrice = _curProObj.msPrice,
                        msScalar = _curProObj.msScalar,
                        buyNum = 1
                    };
                    OrderInfolst.Add(buyProObj);
                }
                //计算总费用
                foreach (var itemPro in OrderInfolst)
                {
                    var _itemPro = (sysMenusDto)itemPro;
                    _CostMoney = _CostMoney + _itemPro.msPrice * _itemPro.buyNum;
                }
                CultureInfo cn = new CultureInfo("zh-CN");
                txtCostMoney.Text = _CostMoney.ToString("c0", cn);
                orderInfoList.ItemsSource = OrderInfolst;
            }
        }
        /// <summary>
        /// 数字按键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnNumClick(object sender, RoutedEventArgs e)
        {
            var _txtnum = txtNum.Text;
            if (sender is Button)
            {
                Button btnObj = (Button)sender;
                var curNumValue = btnObj.Content.ToString();
                if (curNumValue.Equals("."))
                {
                    if (!string.IsNullOrEmpty(_txtnum))
                    {
                        if (_txtnum.IndexOf(".") < 0) _txtnum = _txtnum + curNumValue;
                    }
                    else
                    {
                        Notice.Show("当前取值不合法，请重新取值！", "提示", 3, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    _txtnum = _txtnum + curNumValue;
                }
            }
            txtNum.Text = _txtnum;
            txtNumOrder.Text = _txtnum;
        }
        /// <summary>
        ///  数字删除按键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnNumRemoveClick(object sender, RoutedEventArgs e)
        {
            var _txtnum = txtNum.Text;
            var _cursorPositionIndex = 0;
            if (sender is Button)
            {
                var _tempFuncName = txtNum.Text;

                var _cursorPosition = txtNum.SelectionStart;
                var _selectionLength = txtNum.SelectionLength;
                if (_selectionLength > 0)
                {
                    var _startIndex = _cursorPosition > 0 ? _cursorPosition - 1 : 0;
                    _txtnum = _tempFuncName.Remove(_startIndex, _selectionLength);
                }
                else
                {
                    var _startIndex = _cursorPosition > 0 ? _cursorPosition - 1 : 0;
                    _txtnum = _tempFuncName.Remove(_startIndex, 1);
                }
                _cursorPositionIndex = _cursorPosition;
            }
            txtNum.Text = _txtnum;
            txtNum.Select(_cursorPositionIndex, 0);
            txtNum.Focus();
        }
        /// <summary>
        /// “开台”点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnOpenOrder_Click(object sender, RoutedEventArgs e)
        {
            AddOrder();
        }
        /// <summary>
        ///  增加消费人数事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnNumPlus_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var _inum = 0;
            var _txtNum = txtNum.Text.Trim();
            int.TryParse(_txtNum, out _inum);
            if (_inum >= 0)
            {
                _inum = _inum + 1;
                txtNumOrder.Text = _inum.ToString();
                txtNum.Text = _inum.ToString();
            }
        }
        /// <summary>
        /// 减少消费人数事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnNumSubtract_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var _inum = 0;
            var _txtNum = txtNum.Text.Trim();
            int.TryParse(_txtNum, out _inum);
            if (_inum > 0)
            {
                _inum = _inum - 1;
                txtNumOrder.Text = _inum.ToString();
                txtNum.Text = _inum.ToString();
            }
        }
        /// <summary>
        ///  增加消费数量事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnBuyNumPlus_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var _inum = 0;
            Image curImageObj = (Image)sender;
            StackPanel _buyNumBlock = GetParentObject<StackPanel>(curImageObj, "BuyNumBlock");
            var _buyNumCtr = FindChildCtr<ContentPresenter>(_buyNumBlock, "TextBox");
            var _proIdCtr = FindChildCtr<ContentPresenter>(_buyNumBlock, "TextBlock");
            if (_buyNumCtr != null && _proIdCtr != null)
            {
                var _txtBuyNum = (TextBox)_buyNumCtr;
                var _txtNum = _txtBuyNum.Text.Trim();
                int.TryParse(_txtNum, out _inum);
                if (_inum >= 0)
                {
                    //修改当前消费项目数量
                    _inum = _inum + 1;
                    _txtBuyNum.Text = _inum.ToString();
                    //更新当前所有消费项目集合消费数量
                    string _proId = ((TextBlock)_proIdCtr).Text;
                    OrderInfolst.ForEach(itemUpObj =>
                    {
                        if (itemUpObj.proGuid == _proId)
                        {
                            itemUpObj.buyNum = _inum;
                        }
                    });
                }
            }
        }
        /// <summary>
        /// 减少消费数量事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnBuyNumSubtract_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var _inum = 0;
            Image curImageObj = (Image)sender;
            StackPanel _buyNumBlock = GetParentObject<StackPanel>(curImageObj, "BuyNumBlock");
            var _buyNumCtr = FindChildCtr<ContentPresenter>(_buyNumBlock, "TextBox");
            var _proIdCtr = FindChildCtr<ContentPresenter>(_buyNumBlock, "TextBlock");
            if (_buyNumCtr != null && _proIdCtr != null)
            {
                var _txtBuyNum = (TextBox)_buyNumCtr;
                var _txtNum = _txtBuyNum.Text.Trim();
                int.TryParse(_txtNum, out _inum);
                if (_inum > 1)
                {
                    //修改当前消费项目数量
                    _inum = _inum - 1;
                    _txtBuyNum.Text = _inum.ToString();
                    //更新当前所有消费项目集合消费数量
                    string _proId = ((TextBlock)_proIdCtr).Text;
                    OrderInfolst.ForEach(itemUpObj =>
                    {
                        if (itemUpObj.proGuid == _proId)
                        {
                            itemUpObj.buyNum = _inum;
                        }
                    });
                }
            }
        }
        /// <summary>
        /// 下单操作对应的“用餐人数”控件事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtNumOrder_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!isNumberic(e.Text))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }
        /// <summary>
        /// 下单操作对应的“用餐人数”控件事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtNumOrder_Pasting(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(typeof(String)))
            {
                String text = (String)e.DataObject.GetData(typeof(String));
                if (!isNumberic(text))
                { e.CancelCommand(); }
            }
            else { e.CancelCommand(); }
        }
        /// <summary>
        /// 下单操作对应的“用餐人数”控件事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtNumOrder_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space) e.Handled = true;
        }
        /// <summary>
        /// 取消消费项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnCancelOpenOrderInfo_Click(object sender, RoutedEventArgs e)
        {
            getTableData();
            OpenTableOrderInfo.Visibility = Visibility.Collapsed;
            proList.Visibility = Visibility.Collapsed;
            proTypes.Visibility = Visibility.Collapsed;
            RoomTypes.Visibility = Visibility.Visible;
            tableList.Visibility = Visibility.Visible;
            OpenTableInfo.Visibility = Visibility.Visible;

            OrderInfolst = new List<sysMenusDto>();
            txtNum.Text = "";
            txtNumOrder.Text = "";
            txtRemark.Text = "";
            txtTabProType.Text = "类型";
            chkIsOrderDetail.IsChecked = false;
            orderInfoList.ItemsSource = null;
            CultureInfo cn = new CultureInfo("zh-CN");
            txtCostMoney.Text = _CostMoney.ToString("c0", cn);
        }
        /// <summary>
        /// “开单”消费项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnOpenOrderInfo_Click(object sender, RoutedEventArgs e)
        {
            //0、获取消费人数
            var _costNum = 0;
            int.TryParse(txtNumOrder.Text, out _costNum);
            if (_costNum == 0)
            {
                Notice.Show("请添加要消费的人数！", "提示", 3, MessageBoxIcon.Warning);
                return;
            }

            //1、获取当前餐桌信息
            sysRooms _tabobj = null;
            var _tableNo = btnTableNo.Content;
            var _queryRes = roomservice.GetModelAsync(" rName='" + _tableNo + "' ").Result;
            if (_queryRes.statusCode == (int)ApiEnum.Status)
            {
                _tabobj = _queryRes.data;
            }
            if (_tabobj == null)
            {
                Notice.Show("开单失败！", "提示", 3, MessageBoxIcon.Warning);
                Logger.Default.ProcessError(_queryRes.statusCode, "获取当前餐桌信息出现异常");
                return;
            }

            //2、获取并保存消费项目详情
            //var _costListBlock = (ListBox)orderInfoList;
            //var sysBillConsumes = GetChildObjects(_costListBlock, _tabobj.obId);
            var sysBillConsumes = GetChildObjects(OrderInfolst, _tabobj.obId);
            var _isAddOrder = billConsumeService.AddListAsync(sysBillConsumes).Result;
            if (_isAddOrder.statusCode != (int)ApiEnum.Status)
            {
                Notice.Show("开单失败！", "提示", 3, MessageBoxIcon.Warning);
                Logger.Default.ProcessError(_isAddOrder.statusCode, "保存消费项目详情出现异常");
                return;
            }
            else
            {
                //更新商品的库存量
                List<sysMenusDto> proList = new List<sysMenusDto>();
                foreach (var itemPro in OrderInfolst)
                {
                    var curStock = itemPro.msScalar - itemPro.buyNum;
                    var _proObj = new sysMenusDto
                    {
                        proGuid = itemPro.proGuid,
                        msScalar = curStock >= 0 ? curStock : 0
                    };
                    proList.Add(_proObj);
                }
                var _upStock = menuService.UpProStock(proList).Result;
                if (_upStock.statusCode != (int)ApiEnum.Status)
                {
                    //Notice.Show("开单失败！", "提示", 3, MessageBoxIcon.Warning);
                    Logger.Default.ProcessError(_upStock.statusCode, "更新商品库存出现异常");
                    return;
                }
            }

            //3、保存消费订单
            double _amountCost = 0;//消费总金额
            foreach (var itemCost in sysBillConsumes)
            {
                _amountCost += itemCost.msMoney * itemCost.msAmount;
            }
            var _openOrder = new sysOpenBills
            {
                obGuid = Guid.NewGuid().ToString(),
                obId = _tabobj.obId,
                tName = _tabobj.rName,
                obDate = DateTime.Now,
                obNumber = _costNum,
                mId = "",//未涉及会员业务，暂置为空
                opMoney = _amountCost,
                opSaveMoney = 0,
                opClientPay = 0
            };
            var _openOrderRes = openBillsService.AddAsync(_openOrder).Result;
            if (_openOrderRes.statusCode != (int)ApiEnum.Status)
            {
                Notice.Show("开单失败！", "提示", 3, MessageBoxIcon.Error);
                Logger.Default.ProcessError(_openOrderRes.statusCode, "保存消费订单出现异常");
                return;
            }

            //4、更新餐桌信息：消费人数、开单时间            
            _tabobj.rtNumber = _costNum;
            _tabobj.rtDate = DateTime.Now;
            var _upres = roomservice.UpStateByModel(_tabobj).Result;
            if (_upres.statusCode != (int)ApiEnum.Status)
            {
                Notice.Show("开单失败！", "提示", 3, MessageBoxIcon.Error);
                Logger.Default.ProcessError(_openOrderRes.statusCode, "更新餐桌的“消费人数、开单时间”出现异常");
                return;
            }

            //5、清空开台信息，关闭开单界面，展现餐桌列表
            txtNum.Text = "";
            txtRemark.Text = "";
            btnTableNo.Content = "";
            chkIsOrderDetail.IsChecked = false;
            tableList.Visibility = Visibility.Visible;
            OpenTableInfo.Visibility = Visibility.Visible;
            proList.Visibility = Visibility.Collapsed;
            OpenTableOrderInfo.Visibility = Visibility.Collapsed;
            //ProNumBlock
            Notice.Show("已开单！", "提示", 3, MessageBoxIcon.Success);

            //更新界面餐桌列表状态
            getTableData();
        }
        /// <summary>
        /// “追加消费”事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnContinueCost_Click(object sender, RoutedEventArgs e)
        {
            RoomTypes.Visibility = Visibility.Collapsed;
            OpenTableInfo.Visibility = Visibility.Collapsed;
            tableList.Visibility = Visibility.Collapsed;
            tabInfoHead.Visibility = Visibility.Collapsed;
            proList.Visibility = Visibility.Visible;
            OpenTableOrderInfo.Visibility = Visibility.Visible;
            proTypes.Visibility = Visibility.Visible;
            txtTabProType.Text = "菜品";
            CultureInfo cn = new CultureInfo("zh-CN");
            txtCostMoney.Text = _CostMoney.ToString("c0", cn);
            if (proTypes.Items.Count == 1) GetProCateList();
            GetProList("");
        }
        /// <summary>
        /// “结账”事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnPayment_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //0、获取订单号
                var _orderNo = btnOrderNo.Content.ToString();
                if (string.IsNullOrEmpty(_orderNo))
                {
                    Notice.Show("操作失败，请联系您的管理员！", "提示", 3, MessageBoxIcon.Warning);
                    return;
                }

                //1、获取订单数据
                var _res = openBillsService.GetModelAsync(" obid='" + _orderNo + "' ").Result;
                if (_res.statusCode != (int)ApiEnum.Status)
                {
                    Notice.Show("操作失败，请联系您的管理员！", "提示", 3, MessageBoxIcon.Warning);
                    return;
                }
                var _orderObj = _res.data;
                if (_orderObj == null && string.IsNullOrEmpty(_orderObj.obId))
                {
                    Notice.Show("操作失败，请联系您的管理员！", "提示", 3, MessageBoxIcon.Warning);
                    return;
                }

                //2、更新结账金额
                _orderObj.opClientPay = _orderObj.opMoney;
                _orderObj.lastUpDate = DateTime.Now;
                var upRes = openBillsService.UpAttrAsync(_orderObj).Result;
                if (upRes.statusCode != (int)ApiEnum.Status)
                {
                    Notice.Show("结账失败，请联系您的管理员！", "提示", 3, MessageBoxIcon.Warning);
                    Logger.Default.ProcessError(upRes.statusCode, "更新结账金额出现异常,订单号【" + _orderObj.obId + "】");
                    return;
                }

                //3、更新餐桌状态
                var _tabObjRes = roomservice.GetModelAsync(" rName='" + _orderObj.tName + "' ").Result;
                if (_tabObjRes.statusCode != (int)ApiEnum.Status)
                {
                    Notice.Show("结账失败，请联系您的管理员！", "提示", 3, MessageBoxIcon.Warning);
                    Logger.Default.ProcessError(upRes.statusCode, "根据订单表里的餐桌号获取餐桌信息出现异常,餐桌号【" + _orderObj.tName + "】");
                    return;
                }
                var _tabObj = _tabObjRes.data;
                if (_tabObj == null)
                {
                    Notice.Show("结账失败，请联系您的管理员！", "提示", 3, MessageBoxIcon.Warning);
                    Logger.Default.ProcessError(upRes.statusCode, "根据订单表里的餐桌号获取餐桌信息出现异常,餐桌号【" + _orderObj.tName + "】");
                    return;
                }
                _tabObj.rtState = "空闲";
                _tabObj.rtDate = null;
                _tabObj.rtNumber = null;
                _tabObj.eId = null;
                _tabObj.rtRemark = string.Empty;
                _tabObj.obId = string.Empty;
                var _upTabRes = roomservice.UpAttrAsync(_tabObj).Result;
                if (_tabObjRes.statusCode != (int)ApiEnum.Status)
                {
                    Notice.Show("结账失败，请联系您的管理员！", "提示", 3, MessageBoxIcon.Warning);
                    Logger.Default.ProcessError(upRes.statusCode, "更新餐桌状态出现异常,餐桌号【" + _tabObj.rName + "】");
                }
                else
                {
                    RefshPage();
                    Notice.Show("结账成功！", "提示", 3, MessageBoxIcon.Success);
                }

                #region 弹窗提示操作(已停用)
                //Window AddWin = new AddPayment();
                //if (AddWin != null)
                //{
                //    PaymentParm = btnTableNo.Content.ToString();
                //    (Application.Current.MainWindow as MainWindow).IsMaskVisible = true;
                //    AddWin.Closed += new EventHandler(RefshWin);//注册关闭事件
                //    AddWin.ShowDialog();
                //    (Application.Current.MainWindow as MainWindow).IsMaskVisible = false;
                //}
                #endregion
            }
            catch (Exception ex)
            {
                Notice.Show("结账失败，请联系您的管理员！", "提示", 3, MessageBoxIcon.Warning);
                Logger.Default.Error("更新餐桌状态出现异常", ex);
            }
        }
        private void RefshWin(object sender, EventArgs e)
        {
            //QueryData();
        }
        #endregion

        #region Function
        /// <summary>
        /// 获取餐桌信息
        /// </summary>
        private void getTableData()
        {
            //餐桌类型
            getRoomTypes();
            //餐桌
            getRooms();
        }

        /// <summary>
        /// 获取餐桌类型
        /// </summary>
        /// <param name="selIndex"></param>
        private void getRoomTypes(int selIndex = 0)
        {
            try
            {
                if (RoomTypes.Items.Count == 1)
                {
                    RoomTypes.Items.Clear();
                    TabItem _ti = new TabItem()
                    {
                        Header = "所有餐台",
                        Margin = new Thickness { Left = 0, Top = 0, Right = 10, Bottom = 0 },
                        Padding = new Thickness { Left = 25, Right = 30, Top = 5, Bottom = 5 }
                    };
                    RoomTypes.Items.Add(_ti);
                    var _tabTypeService = new sysRoomTypeService();
                    var _parm = new ParmString { parm = "" };
                    var _tabRest = _tabTypeService.QueryList(_parm).Result;
                    if (_tabRest.statusCode == (int)ApiEnum.Status)
                    {
                        var _roomTypes = _tabRest.data;
                        if (_roomTypes != null)
                        {
                            foreach (var roomTypeObj in _roomTypes)
                            {
                                var bgc = new BrushConverter();
                                TabItem ti = new TabItem()
                                {
                                    Header = roomTypeObj.rtName,
                                    Margin = new Thickness { Left = 0, Top = 0, Right = 10, Bottom = 0 },
                                    Padding = new Thickness { Left = 25, Right = 30, Top = 5, Bottom = 5 }
                                };
                                RoomTypes.Items.Add(ti);
                            }
                        }
                    }
                    else
                    {
                        Notice.Show("系统连接失败，请联系您的管理员！", "提示", 3, MessageBoxIcon.Info);
                        Logger.Default.ProcessError(_tabRest.statusCode, "没有获取到餐桌类型数据");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取餐桌类型出现异常", ex);
            }
        }

        /// <summary>
        /// 获取餐桌类型对应的所有餐桌
        /// </summary>
        /// <param name="rtid"></param>
        /// <param name="rtstate"></param>
        private void getRooms(string rtid = "", int rtstate = -1)
        {
            try
            {
                TableDataList = new List<TableModel>();
                var parms = new PageParm { typesId = rtid, types = rtstate };
                var _tabRes = roomservice.QueryListByType(parms).Result;
                if (_tabRes.statusCode == (int)ApiEnum.Status)
                {
                    var rooms = _tabRes.data;
                    if (rooms != null)
                    {
                        foreach (var roomObj in rooms)
                        {
                            var _time = "0分钟";
                            if (roomObj.rtDate != null) _time = DateHelp.DateDiffMinutes(DateTime.Now, Convert.ToDateTime(roomObj.rtDate));
                            var _tbState = "#cccccc";
                            var _tbStateName = "空闲";
                            switch (roomObj.rtState)
                            {
                                case "占用":
                                    _tbState = "#C800AAFF";
                                    _tbStateName = "用餐中";
                                    break;
                                case "预定":
                                    _tbState = "green";
                                    _tbStateName = "预约中";
                                    _time = "0分钟";
                                    break;
                                case "脏台":
                                    _tbState = "red";
                                    _tbStateName = "待清理";
                                    _time = "0分钟";
                                    break;
                                case "停用":
                                    _tbState = "black";
                                    _tbStateName = "已停用";
                                    _time = "0分钟";
                                    break;
                            }

                            var _obj = new TableModel()
                            {
                                tbName = roomObj.rName,
                                tbMaxNum = roomObj.rtNumber != null ? (int)roomObj.rtNumber : 0,
                                userTime = _time,
                                tbStateColor = _tbState,
                                tbStateName = _tbStateName,
                                tbId = roomObj.rId,
                                tbOrderNo = roomObj.obId
                            };
                            TableDataList.Add(_obj);
                        }
                    }
                    tableList.ItemsSource = TableDataList;
                }
                else
                {
                    Notice.Show("系统连接失败，请联系您的管理员！", "提示", 3, MessageBoxIcon.Warning);
                    Logger.Default.ProcessError(_tabRes.statusCode, "没有获取餐桌类型对应的所有餐桌");
                }
            }
            catch (Exception ex)
            {
                Logger.Default.Error("获取餐桌类型对应的所有餐桌出现异常", ex);
            }
        }

        /// <summary>
        /// 获取单个餐桌详情
        /// </summary>
        /// <param name="rtName"></param>
        private void GetDetail(string strOrder)
        {
            try
            {
                double _msMoney = 0;
                var parms = new ParmString { parm = strOrder };
                var _tabInfoRes = roomservice.GetTabCostdetails(parms).Result;
                if (_tabInfoRes.statusCode == (int)ApiEnum.Status)
                {
                    var TableDetailList = _tabInfoRes.data;
                    if (TableDetailList != null)
                    {
                        btnPayment.Visibility = Visibility.Visible;
                        foreach (var item in TableDetailList)
                        {
                            _msMoney = _msMoney + item.msMoney;
                        }
                    }
                    else
                    {
                        btnPayment.Visibility = Visibility.Collapsed;
                    }
                    txtAmountMoney.Text = _msMoney.ToString();
                    tableInfoList.ItemsSource = TableDetailList;
                }
                else
                {
                    Logger.Default.ProcessError(_tabInfoRes.statusCode, "获取单个餐桌消费详情出现异常");
                }
            }
            catch (Exception ex)
            {
                Notice.Show("查询失败！", "提示", 3, MessageBoxIcon.Warning);
                Logger.Default.Error("获取单个餐桌消费详情出现异常", ex);
            }
        }

        /// <summary>
        /// 获取商品类型
        /// </summary>
        private void GetProCateList()
        {
            try
            {
                proTypes.Items.Clear();
                TabItem _ti = new TabItem()
                {
                    Header = "所有菜品",
                    Uid = "",
                    Margin = new Thickness { Left = 0, Top = 0, Right = 10, Bottom = 0 },
                    Padding = new Thickness { Left = 25, Right = 30, Top = 5, Bottom = 5 }
                };
                proTypes.Items.Add(_ti);

                var parms = new ParmString { parm = "" };
                var _menuTypeRes = menutypeService.QueryMenuTypes(parms).Result;
                if (_menuTypeRes.statusCode == (int)ApiEnum.Status)
                {
                    var prots = _menuTypeRes.data;
                    if (prots != null)
                    {
                        foreach (var _typeObj in prots)
                        {
                            var bgc = new BrushConverter();
                            TabItem ti = new TabItem()
                            {
                                Header = _typeObj.mtName,
                                Uid = _typeObj.mtGuid.ToString(),
                                Margin = new Thickness { Left = 0, Top = 0, Right = 10, Bottom = 0 },
                                Padding = new Thickness { Left = 25, Right = 30, Top = 5, Bottom = 5 }
                            };
                            proTypes.Items.Add(ti);
                        }
                    }
                }
                else
                {
                    Logger.Default.ProcessError(_menuTypeRes.statusCode, "获取菜单类型异常");
                }
            }
            catch (Exception ex)
            {
                Logger.Default.Error("菜品类型查询异常", ex);
                Notice.Show("菜品类型查询失败！", "提示", 3, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        private void GetProList(string protype)
        {
            try
            {
                var _parms = new ParmString { parm = protype };
                var _res = menuService.QueryMenusByMtId(_parms).Result;
                if (_res.statusCode == (int)ApiEnum.Status)
                {
                    var _datas = _res.data;
                    if (_datas != null)
                    {
                        proList.Visibility = Visibility.Visible;
                        proList.ItemsSource = _datas;
                    }
                }
                else
                {
                    Notice.Show("没有找到对应的菜品", "提示", 3, MessageBoxIcon.Info);
                    Logger.Default.ProcessError(_res.statusCode, "根据商品类型获取商品异常");
                }
            }
            catch (Exception ex)
            {
                Notice.Show("没有找到对应的菜品", "提示", 3, MessageBoxIcon.Info);
                Logger.Default.Error("根据商品类型获取商品异常", ex);
            }
        }

        /// <summary>
        /// 生成订单
        /// </summary>
        private void AddOrder()
        {
            var _iUNum = 0;
            var _userNum = txtNum.Text.Trim();
            int.TryParse(_userNum, out _iUNum);
            var _tableName = btnTableNo.Content.ToString();
            if (string.IsNullOrEmpty(_tableName))
            {
                Notice.Show("请选择需要开单的餐桌！", "提示", 3, MessageBoxIcon.Info);
                return;
            }
            if (_iUNum == 0)
            {
                Notice.Show("请录入要消费的人数！", "提示", 3, MessageBoxIcon.Info);
                return;
            }
            try
            {
                var _rId = 0; int.TryParse(btnTableNo.Uid, out _rId);
                if (_rId > 0)
                {
                    var _orderNo = string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now);
                    sysRooms upTabObj = new sysRooms();
                    upTabObj.rId = _rId;
                    upTabObj.rtState = "占用";
                    upTabObj.rtRemark = txtRemark.Text;
                    upTabObj.rtNumber = _iUNum;
                    upTabObj.obId = _orderNo;
                    var _upRes = roomservice.UpStateById(upTabObj).Result;
                    if (_upRes.statusCode == (int)ApiEnum.Status)
                    {
                        //开台成功后，是否需要“开单”
                        var _isOpenCostOrder = (bool)chkIsOrderDetail.IsChecked;
                        if (_isOpenCostOrder)
                        {
                            RoomTypes.Visibility = Visibility.Collapsed;
                            tableList.Visibility = Visibility.Collapsed;
                            OpenTableInfo.Visibility = Visibility.Collapsed;
                            OpenTableOrderInfo.Visibility = Visibility.Visible;
                            proTypes.Visibility = Visibility.Visible;
                            txtTabProType.Text = "菜品";
                            CultureInfo cn = new CultureInfo("zh-CN");
                            txtCostMoney.Text = _CostMoney.ToString("c0", cn);

                            if (proTypes.Items.Count == 1) GetProCateList();
                            GetProList("");
                            Notice.Show("开台成功！", "提示", 3, MessageBoxIcon.Success);
                        }
                        else
                        {
                            getTableData();
                        }
                    }
                    else
                    {
                        Notice.Show("开台失败！", "提示", 3, MessageBoxIcon.Error);
                        Logger.Default.ProcessError(_upRes.statusCode, "开台失败！");
                    }
                }
                else
                {
                    Logger.Default.ProcessError((int)ApiEnum.Error, "没有找到对应的餐桌编号！");
                }
            }
            catch (Exception ex)
            {
                Notice.Show("开台失败！", "提示", 3, MessageBoxIcon.Error);
                Logger.Default.Error("开台出现异常。", ex);
                return;
            }
        }

        /// <summary>
        /// 寻找子控件
        /// </summary>
        /// <typeparam name="childItem"></typeparam>
        /// <param name="obj">父级控件</param>
        /// <param name="ctrtype">子控件类型名</param>
        /// <returns></returns>
        private object FindChildCtr<childItem>(DependencyObject obj, string ctrtype) where childItem : DependencyObject
        {
            var _childLen = VisualTreeHelper.GetChildrenCount(obj);
            for (int i = 0; i < _childLen; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child.DependencyObjectType.SystemType.Name == ctrtype)
                {
                    return child;
                }
            }
            return null;
        }

        /// <summary>
        /// 寻找集合控件的子控件
        /// </summary>
        /// <typeparam name="childItem"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
        {
            var _childLen = VisualTreeHelper.GetChildrenCount(obj);
            for (int i = 0; i < _childLen; i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem) return (childItem)child;
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null) return childOfChild;
                }
            }
            return null;
        }

        /// <summary>
        /// 寻找某个控件的父级控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public T GetParentObject<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            DependencyObject parent = VisualTreeHelper.GetParent(obj);
            while (parent != null)
            {
                if (parent is T && (((T)parent).Name == name | string.IsNullOrEmpty(name)))
                {
                    return (T)parent;
                }
                parent = VisualTreeHelper.GetParent(parent);
            }
            return null;
        }

        /// <summary>
        /// 获取消费清单里的消费项目集合(暂停用)
        /// </summary>
        /// <typeparam name="childItem"></typeparam>
        /// <param name="obj"></param>
        /// <param name="control"></param>
        /// <returns></returns>
        private List<sysBillConsume> GetChildObjects(ListBox obj, string orderId)
        {
            List<sysBillConsume> sysBillConsumes = new List<sysBillConsume>();
            foreach (var item in obj.Items)
            {
                var _curObj = (sysMenusDto)item;
                var _addOrderObj = new sysBillConsumeDto
                {
                    bcGuid = Guid.NewGuid().ToString(),
                    obId = orderId,
                    msId = _curObj.proGuid,
                    msAmount = _curObj.buyNum,//???
                    msMoney = _curObj.msPrice,
                    msTime = DateTime.Now
                };
                sysBillConsumes.Add(_addOrderObj);
            }
            return sysBillConsumes;
        }
        private List<sysBillConsume> GetChildObjects(List<sysMenusDto> selProList, string orderId)
        {
            List<sysBillConsume> sysBillConsumes = new List<sysBillConsume>();
            foreach (var item in selProList)
            {
                var _curObj = (sysMenusDto)item;
                var _addOrderObj = new sysBillConsume
                {
                    bcGuid = Guid.NewGuid().ToString(),
                    obId = orderId,
                    msId = _curObj.proGuid,
                    msAmount = _curObj.buyNum,
                    msMoney = _curObj.msPrice,
                    msTime = DateTime.Now
                };
                sysBillConsumes.Add(_addOrderObj);
            }
            return sysBillConsumes;
        }

        /// <summary>
        /// 判断字符是否为数字
        /// </summary>
        /// <param name="_string"></param>
        /// <returns></returns>
        public static bool isNumberic(string _string)
        {
            if (string.IsNullOrEmpty(_string))
                return false;
            foreach (char c in _string)
            {
                if (!char.IsDigit(c))
                    //if(c<'0' c="">'9')//最好的方法,在下面测试数据中再加一个0，然后这种方法效率会搞10毫秒左右
                    return false;
            }
            return true;
        }

        /// <summary>
        /// 刷新窗体
        /// </summary>
        private void RefshPage()
        {
            getTableData();
            OpenTableOrderInfo.Visibility = Visibility.Collapsed;
            proList.Visibility = Visibility.Collapsed;
            proTypes.Visibility = Visibility.Collapsed;
            RoomTypes.Visibility = Visibility.Visible;
            tableList.Visibility = Visibility.Visible;
            OpenTableInfo.Visibility = Visibility.Visible;

            OrderInfolst = new List<sysMenusDto>();
            txtNum.Text = "";
            txtNumOrder.Text = "";
            txtRemark.Text = "";
            btnOrderNo.Content = "";
            btnTableNo.Content = "";
            txtTabProType.Text = "类型";
            chkIsOrderDetail.IsChecked = false;
            orderInfoList.ItemsSource = null;
            CultureInfo cn = new CultureInfo("zh-CN");
            txtCostMoney.Text = _CostMoney.ToString("c0", cn);
        }
        #endregion
    }
}
